﻿using UnityEngine;
using UnityEngine.UI;

namespace ZCUIManager
{
    /// <summary>
    /// UI都继承该类
    /// </summary>
    public class UIBaseGraphic : Graphic
    {
        #region 
        [SerializeField] protected Texture m_Texture;
        #endregion

        #region Graphic Override Method
        /// <summary>
        /// 重写mainTexture
        /// </summary>
        public override Texture mainTexture
        {
            get
            {
                if (m_Texture == null)
                {
                    return base.mainTexture;
                }
                return m_Texture;
            }
        }

        /// <summary>
        /// 重写OnPopulateMesh
        /// </summary>
        /// <param name="vh"></param>
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            Texture tex = mainTexture;
            vh.Clear();
            if (tex != null)
            {
                var r = GetPixelAdjustedRect();
                var v = new Vector4(r.x, r.y, r.x + r.width, r.y + r.height);
                var scaleX = tex.width * tex.texelSize.x;
                var scaleY = tex.height * tex.texelSize.y;
                {
                    var color32 = color;
                    vh.AddVert(new Vector3(v.x, v.y), color32, new Vector2(0, 0));
                    vh.AddVert(new Vector3(v.x, v.w), color32, new Vector2(0, scaleY));
                    vh.AddVert(new Vector3(v.z, v.w), color32, new Vector2(scaleX, scaleY));
                    vh.AddVert(new Vector3(v.z, v.y), color32, new Vector2(scaleX, 0));

                    vh.AddTriangle(0, 1, 2);
                    vh.AddTriangle(2, 3, 0);
                }
            }
        }
        #endregion
    }
}
